﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BlogLite.Models.Database;

namespace BlogLite.Models
{
    public class BlogLiteRepository : IBlogLiteRepository
    {
        BlogLiteContext db = new BlogLiteContext();

        public IEnumerable<aspnet_Users> MembershipUsers
        {
            get { return db.MembershipUsers; }
        }

        public IEnumerable<Post> Posts
        {
            get { return db.Posts.OrderByDescending(p => p.PostDate); }
        }

        public IEnumerable<Tag> Tags
        {
            get { return db.Tags.OrderBy(t => t.TagName); }
        }

        public void AddPost(Post post)
        {
            db.Posts.Add(post);
        }

        public void AddUser(User user)
        {
            db.Users.Add(user);
        }

        public aspnet_Users GetMembershipUserByUsername(string username)
        {
            return db.MembershipUsers.SingleOrDefault(u => u.Username == username);
        }

        public Post GetPostByPostId(int postId)
        {
            return db.Posts.SingleOrDefault(p => p.PostId == postId);
        }        

        public Tag GetTagByTagId(int tagId)
        {
            return db.Tags.SingleOrDefault(t => t.TagId == tagId);
        }

        public User GetUserByUsername(string username)
        {
            var membershipUser = GetMembershipUserByUsername(username);
            return db.Users.SingleOrDefault(u => u.aspnet_User.PKID == membershipUser.PKID);
        }

        public void Save()
        {
            db.SaveChanges();
        }
    }
}